import { useEffect, useState } from 'react'
import api from '../api'
import { useNavigate } from 'react-router-dom'
function LoginAndRegister () {
    const navigate = useNavigate()
    const [username, setUsername] = useState('')
    const [pasword, setPassword] = useState('')
    const [errorMessage, setErrorMessage] = useState('')
    const handleChangeUsername = (e) => {
        setUsername(e.target.value)
    }
    const handleChangePassword = (e) => {
        setPassword(e.target.value)
    }

    // useEffect(() => {
        const login = async () => {
            try {
              const res = await api.axios.post(api.url.login, {
                "username": username,
                  "password": pasword
              });
              let response = res.data
              if(response.code === 0) {
                  //   sessionStorage.setItem('token', response.token )
                    sessionStorage.setItem('user', JSON.stringify(response.data))
                    console.log('login', response);
                    navigate('/')
              } else {
                setErrorMessage(response.message)
              }
            } catch (error) {
              console.log(error);
            }
        };
        
        


    // })
    const handleSubmit = (event) => {
        event.preventDefault();

        login();
    }
    return (
        <div className="auth-page">
            <div className="container page">
                <div className="row">
                    <div className="col-md-6 offset-md-3 col-xs-12">
                        <h1 className="text-xs-center">Sign in</h1>
                        <p className="text-xs-center">
                            <a href="/register">Need an account?</a>
                        </p>
                        {
                            errorMessage && <ul className="error-messages">
                            <li>{errorMessage}</li>
                        </ul>
                        }
                        
                        <form >
                            <fieldset className="form-group">
                                <input className="form-control form-control-lg" type="text" value={username} onChange={handleChangeUsername} placeholder="Username" />
                            </fieldset>
                            <fieldset className="form-group">
                                <input className="form-control form-control-lg" type="text" value={pasword} onChange={handleChangePassword} placeholder="Password" />
                            </fieldset>
                            <button className="btn btn-lg btn-primary pull-xs-right" onClick={handleSubmit}>Sign in</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default LoginAndRegister;